﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OT.Data;
using OT.Areas.Admin.Models;
using PagedList;
namespace OT.Areas.Admin.Controllers
{
    public class UserController : Controller
    {
        #region Declaration
        readonly OTEntitiesme OTDb = new OTEntitiesme();
        #endregion

        #region Index
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(int pageNumber, int pageSize, string searchString, int pgindex)
        {
            List<Users> usr = (from c in OTDb.Users
                               join sc in OTDb.Cities
                               on c.CityID equals sc.CityID into output
                               join qt in OTDb.UserTypes
                                  on c.UserTypeID equals qt.UserTypeID
                               from j in output.DefaultIfEmpty()
                               select new Users
                               {
                                   UserID = (int)c.UserID,
                                   FirstName = c.FirstName,
                                   LastName = c.LastName,
                                   Address = c.Address,
                                   EmailAddress = c.EmailAddress,
                                   UserType1 = qt.UserType1,
                                   MobileNo = c.MobileNo,
                                   LandlineNo = c.LandlineNo,
                                   //CountryID =(int) c.CountryID,
                                   //StateID =(int) c.StateID,
                                   CityName = j.CityName,
                                   Status = (bool)c.Status,
                                   //RememberMe = c.RememberMe,
                                   LastLoginDate = (c.LastLoginDate.HasValue) ? c.LastLoginDate.Value : DateTime.MinValue,
                                   CreatedDate = (c.CreatedDate.HasValue) ? c.CreatedDate.Value : DateTime.MinValue,
                                   UpdatedDate = (c.UpdatedDate.HasValue) ? c.UpdatedDate.Value : DateTime.MinValue
                                  }).OrderBy(o => o.FirstName).ToList<Users>(); ;
            if (!string.IsNullOrEmpty(searchString))
                usr = usr.Where(r => r.FirstName.ToLower().Contains(searchString.ToLower())).ToList();
            int recount =  usr.Count;
            usr = usr.Skip<Users>(pgindex * (pageNumber - 1))
                .Take<Users>(pgindex).ToList<Users>();
            return Json(new
            {
                PageNumber = pageNumber,
                PageSize = pageSize,
                PgIndex = pgindex,
                Data = usr,
                RecordCount = recount
            });
        }
        #endregion

        #region Create
        public ActionResult Create()
        {
            Users User = null;
            try
            {
                User = new Users();
                var usertyp = OTDb.UserTypes.ToList();
                User.UserTypes = usertyp;
                var Country = OTDb.Countries.ToList();
                User.Countrys = Country;
                var Stats = OTDb.States.Where(p=>p.CountryID == p.Country.CountryID).ToList();
                User.States = Stats;
                var City = OTDb.Cities.Where(p=>p.StateID == p.State.StateID).ToList();
                User.Citys = City;
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return PartialView(User);
        }
        #region EncodeDecode
        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

        public static string Base64Decode(string base64EncodedData)
        {
            var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }
        #endregion
        [HttpPost]
        public string Create(String FirstName, string LastName, String Address, string EmailAddress, string Password, string MobileNo, string LandlineNo, int CountryID, Boolean Status, Boolean RememberMe, int UserTypeID, int StateID = 0, int CityID = 0)
        {
            string result = "";
            User us = null;
            try
            {
                if (ModelState.IsValid)
                {
                    us = new User();
                    us.FirstName = FirstName;
                    us.LastName = LastName;
                    us.Address = Address;
                    us.EmailAddress =Base64Decode(EmailAddress) ;
                    us.Password = Password;
                    us.MobileNo = MobileNo;
                    us.LandlineNo = LandlineNo;
                    us.CountryID = CountryID;
                    us.StateID = StateID;
                    us.CityID = CityID;
                    us.Status = Status;
                    us.RememberMe = RememberMe;
                    us.UserTypeID = UserTypeID;
                    us.LastLoginDate = DateTime.Now;
                    us.CreatedDate = DateTime.Now;
                    us.UpdatedDate = DateTime.Now;
                    OTDb.Users.Add(us);
                    OTDb.SaveChanges();
                    result = "Sucess";
                }
                else
                {
                    var Citys = OTDb.Users.ToList();
                    result = "NotValid";
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return result;
        }
        #endregion

        #region Edit
        public ActionResult Edit(int UserID)
        {
            Users us = null;
            try
            {
                var categry = OTDb.Users.Where(r => r.UserID == UserID).SingleOrDefault();
                if (categry != null)
                {
                    us = new Users();
                    us.FirstName = categry.FirstName;
                    us.LastName = categry.LastName;
                    us.MobileNo = categry.MobileNo;
                    us.LandlineNo = categry.LandlineNo;
                    us.UserID = categry.UserID;
                    us.Status = (bool)categry.Status;
                    us.Address = categry.Address;
                    us.EmailAddress = categry.EmailAddress;
                    us.StateID = (int)categry.StateID;
                    us.CityID = (int)categry.CityID;
                    us.CountryID = (int)categry.CountryID;
                    us.UserTypeID = (int)categry.UserTypeID;
                    var usertyp = OTDb.UserTypes.ToList();
                    us.UserTypes = usertyp;
                    var Country = OTDb.Countries.ToList();
                    us.Countrys = Country;
                    var Stats = OTDb.States.Where(p=>p.CountryID==categry.CountryID).ToList();
                    us.States = Stats;
                    var City = OTDb.Cities.Where(p=>p.StateID==categry.StateID).ToList();
                    us.Citys = City;
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return PartialView(us);
        }
        [HttpPost]
        public string Edit(int UserID,String FirstName, string LastName, String Address, string EmailAddress, string Password, string MobileNo, string LandlineNo, int CountryID, int StateID, int CityID, Boolean Status, Boolean RememberMe, int UserTypeID)
        {
            string result = "";
            try
            {
                if (ModelState.IsValid)
                {
                    var us = OTDb.Users.Where(r => r.UserID == UserID).SingleOrDefault();
                    if (us != null)
                    {
                        us.FirstName = FirstName;
                        us.LastName = LastName;
                        us.Address = Address;
                        us.EmailAddress = Base64Decode(EmailAddress);
                        if (Password == string.Empty)
                        {
                            us.Password = us.Password;
                        }
                        else
                        {
                            us.Password = Password;
                        }
                        us.MobileNo = MobileNo;
                        us.LandlineNo = LandlineNo;
                        us.CountryID = CountryID;
                        us.StateID = StateID;
                        us.CityID = CityID;
                        us.Status = Status;
                        us.RememberMe = RememberMe;
                        us.UserTypeID = UserTypeID;
                        us.LastLoginDate = DateTime.Now;
                        us.UpdatedDate = DateTime.Now;
                        OTDb.SaveChanges();
                        result = "Sucess";
                    }
                }
                else
                {
                    result = "NotValid";
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return result;
        }
        #endregion

        #region ExtraCall
        private IList<State> GetState(int CountryID)
        {
            return OTDb.States.Where(m => m.CountryID == CountryID).ToList();
        }
        private IList<City> GetCity(int StateID)
        {
            return OTDb.Cities.Where(c => c.StateID == StateID).ToList();
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadState(string CountryID)
        {
            var stateList = this.GetState(Convert.ToInt32(CountryID));
            var stateData = stateList.Select(m => new SelectListItem()
            {
                Text = m.StateName,
                Value = m.StateID.ToString(),
            });
            return Json(stateData, JsonRequestBehavior.AllowGet);
        }
      
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadCity(string StateID)
        {
            var CityList = this.GetCity(Convert.ToInt32(StateID));
            var CityData = CityList.Select(c => new SelectListItem()
            {
                Text = c.CityName,
                Value = c.CityID.ToString(),
            });
            return Json(CityData, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Delete
        public ActionResult Delete(int UserID)
        {
            Users topc = null; 
            try
            {
                var categry = OTDb.Users.Where(r => r.UserID == UserID).SingleOrDefault();
                if (categry != null)
                {
                    topc = new Users();
                    topc.UserID = categry.UserID;
                    topc.FirstName = categry.FirstName;
                    topc.LastName = categry.LastName;
                    topc.Status = (bool)categry.Status;
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return PartialView(topc);
        }
        [HttpPost]
        public string Delete(int UserID, string IsDelete)
        {
            string result = "";
            try
            {
                var cat = OTDb.Users.Where(r => r.UserID == UserID).SingleOrDefault();
                if (cat != null)
                {
                    OTDb.Users.Remove(cat);
                    OTDb.SaveChanges();
                    result = "Success";
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return result;
        }
        #endregion
        //public Users user { get; set; }
    }
}


